/**
 * Created by hcadmin on 16/5/16.
 */
define([
    "jquery",
    "IO",
    "UPLOADUI",
    "UPLOAD",
    "jqueryUI",
    "bootbox"
], function($,IO,jui,upui,up,bootbox,definebt) {

    //卡券的表格
    $(function () {
        var grid;
        //每列数据列性
        var columns = [
            {
                title: '卡券名',
                dataIndex: 'coupon_name',
                dataSource: function (data, datarow, gridobj, current_column) {
                    //console.log("卡券名",data[datarow].coupon_name);
                    return "<span>" + data[datarow].coupon_name + "</span>";
                }
            },
            {
                title: '折扣',
                dataIndex: 'discount',
                dataSource: function (data, datarow, gridobj, current_column) {
                    var discount = data[datarow].discount;
                    var discountStr = '0';
                    if (discount > 0){
                        discount = discount * 100;
                        discountStr = '' + discount + '%';
                    }
                    return "<span>" + discountStr + "</span>";
                }
            },
            {
                title: '领取状态',
                dataIndex: 'status',
                dataSource: function (data, datarow, gridobj, current_column) {
                    var status = '未开始领取';
                    if (data[datarow].status != 2){
                        status = '可领取';
                    }else{
                        status = '领取结束';
                    }
                    return "<span>" +status + "</span>";
                }
            },
            {
                title: '已售',
                dataIndex: 'currentCount',
                dataSource: function (data, datarow, gridobj, current_column) {
                    //var saleCount = data[datarow].totalcount - data[datarow].currentcount;
                    return "<span>" + data[datarow].currentcount + "</span>";
                }
            },
            {
                title: '库存',
                dataIndex: 'totalCount',
                dataSource: function (data, datarow, gridobj, current_column) {
                    return "<span>" + data[datarow].remaincount + "</span>";
                }
            },
            {
                title: '操作',
                dataIndex: 'action',
                dataSource: function (data, datarow, gridobj, current_column) {
                    return "<a href='javascript:void(0)' class='detial' act_id='"+data[datarow].coupon_temp_id+"'><span style='color: #6ab7ad;'>" + "详情" + "</span></a>"
                        + "&nbsp;<a href='javascript:void(0)' class = 'edit' act_id = '"+data[datarow].coupon_temp_id+"'><span style='color: #d47c7b;'>" + "编辑</span></a>";
                }
            },

        ];


        //数组初始化

        function dataInit() {
            var discount = $("#category1 option:selected").attr("data-id");
            var status = $("#category2 option:selected").attr("data-id");
            if (status == 1){
                status = 2;
            }
            grid = new Grid("/api/coupons/list?discount="+discount+"&status="+status, $("#table_my_toast"), $("#paging_my_toast"), 1, 10, columns, get_input_param(), 10);

            //初始化
            grid.Init();
        }

        //获取输入框内容
        function get_input_param() {

            var param='';
            return param;
        }
        dataInit();

        //查询
        $("#query").bind("click", function () {
            dataInit();
        });



    });

    //添加卡券
    $("#addcoupon").bind("click", function () {
        $("#addCouponModal").modal();
    });

    //卡券照片上传
    $('#fileupload1').fileupload({
        url: '/upload',
        dataType: 'json',
        autoUpload: true,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        maxFileSize: 10000000, // 10 MB
        disableImageResize: /Android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
        previewMaxWidth: 150,
        previewMaxHeight: 150,
        previewCrop: true
    }).on('fileuploadadd', function (e, data) {
        document.getElementById('upimgs3').src = '/images/loading.gif';
    }).on('fileuploadprocessalways', function (e, data) {
        //console.log("fileuploadprocessalways",data);
    }).on('fileuploadprogressall', function (e, data) {
        //console.log("fileuploadprogressall",data);
    }).on('fileuploaddone', function (e, data) {
        var alt = $(e.target).attr('alt');
        if (!alt)
            alt = '';
        //console.log("#upimgs3" + alt);
        $("#upimgs3" + alt).attr("src", data._response.result.url);

    });

    //确定添加卡券
    $("#commitCoupon").bind("click",function(){
        var name = $("#AddCouponName").val();
        var start_time = $("#AddCouponTime1").val();
        var end_time = $("#AddCouponTime2").val();
        var timeLimit = document.getElementsByName("timeLimit");
        var timeLimitStr = '0';
        for (var i = 0;i <timeLimit.length;i++){
            if (timeLimit[i].checked){
                timeLimitStr = timeLimit[i].value;
            }
        }
        var effective_time = $("#AddEffective_time").val();
        var couponDiscount = $("#AddCouponDiscount").val();
        var AddCouponLimit_count = $("#AddCouponLimit_count").val();
        var couponQuantity = $("#AddCouponQuantity").val();
        var isLimit_count = document.getElementsByName("isLimit_count");
        for (var i = 0;i <isLimit_count.length;i++){
            if (isLimit_count[i].checked){
                AddCouponLimit_count = isLimit_count[i].value;
            }
        }
        var isCouponQuantity = document.getElementsByName("isCouponQuantity");
        for (var i = 0;i <isCouponQuantity.length;i++){
            if (isCouponQuantity[i].checked){
                couponQuantity = isCouponQuantity[i].value;
            }
        }

        var range = document.getElementsByName("range");
        var rangeStr='';
        for (var i = 0;i <range.length;i++){
            if (range[i].checked){
                rangeStr = range[i].value;
            }
        }
        var form = document.getElementsByName("form");
        var formStr='';
        for (var i = 0;i <form.length;i++){
            if (form[i].checked){
                formStr = form[i].value;
            }
        }
        var price = $("#addPrice").val()
        var couponInstro = document.getElementById("couponInstro").value;

        var coupon_pic = $("#upimgs3").attr("src");


        if (name == ''){
            alert("请填写卡券名");
            return;
        }
        if (timeLimitStr == '0'){
            if (start_time == ''){
                alert("请填写可领取时间");
                return;
            }
            if (end_time == ''){
                alert("请填写可领取时间");
                return;
            }
            start_time += " 00:00:00";
            end_time += " 00:00:00";
        }else{
            var date = new Date();
            start_time = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate() + ' 00:00:00';
            end_time = '2999-1-1 00:00:00';
            //start_time = '';
            //end_time = '';
        }
        if (effective_time == ''){
            alert("请填写有效时间");
            return;
        }
        if (couponDiscount == ''){
            alert("请填写折扣面额");
            return;
        }else{
            couponDiscount = parseInt(couponDiscount)/100;
        }
        if (AddCouponLimit_count == ''){
            alert("请填写使用次数");
            return;
        }
        if (couponQuantity == ''){
            alert("请填写发行量");
            return;
        }
        if (rangeStr == ''){
            alert("请选择通用范围");
            return;
        }
        if (formStr == ''){
            alert("请选择卡券获取形式");
            return;
        }
        if (couponInstro == ''){
            alert("请填写详细介绍");
            return;
        }
        if (coupon_pic == '/images/ylm.png'){
            alert("请上传卡券图片");
            return;
        }
        var params = {name:name,start_time:start_time,end_time:end_time,timeLimitStr:timeLimitStr,
            effective_time:effective_time,couponDiscount:couponDiscount,AddCouponLimit_count:AddCouponLimit_count,couponQuantity:couponQuantity,rangeStr:rangeStr,formStr:formStr,price:price,couponInstro:couponInstro,coupon_pic:coupon_pic};
        //console.log("参数",params);
        bootbox.confirm("确定添加该卡券?",function(result) {
            if (result) {
                IO.get("/api/addCoupon", params, function (data) {
                    bootbox.alert(data.msg, function () {
                        if (data.code == 0) {
                            location.href = '/96053/card';
                        }
                    })
                })

            }
        })
    });

    //卡券详情
    $(document).on("click",".detial",function() {
        var act_id = $(this).attr("act_id");
        $("#CouponDetialModal").modal();
        IO.get("/api/couponDetial",{act_id:act_id},function(data){
            $("#CouponName").val(data.data.coupon_name);
            var startTime = data.data.dole_start_time.substring(0,10);
            var timeArry1 = startTime.split("/")
            startTime = timeArry1.join("-");
            var endTime = data.data.dole_end_time.substring(0,10);
            timeArry2= endTime.split("/")
            endTime = timeArry2.join("-");
            $("#CouponTime1").val(startTime);
            $("#CouponTime2").val(endTime);
            if (endTime == '2999-01-01'){
                var forever = document.getElementsByName("timeLimit2");
                forever[0].checked = true;
            }
            $("#Effective_time").val(data.data.day);
            $("#CouponDiscount").val(data.data.discount*100);
            var totalCount = data.data.totalcount;
            var countLimt = document.getElementsByName("isCouponQuantity2");

            if (totalCount != -1){
                $("#CouponQuantity").val(data.data.totalcount);
                countLimt[0].checked = false;
            }else{
                countLimt[0].checked = true;
            }
            var useLimt = data.data.limit_count;
            var Limt = document.getElementsByName("isLimit_count2");
            if (useLimt != -1){
                $("#CouponLimit_count").val(data.data.limit_count);
                Limt[0].checked = false;
            }else{
                Limt[0].checked = true;
            }
            document.getElementById("couponInstro2").value = data.data.coupon_desc;
            $("#upimgs4").attr("src",data.data.coupon_cover);
            var rang = document.getElementsByName("range2");
            //data.data.coupon_type = 3;
            for (var i = 1;i<rang.length+1;i++){
                if (data.data.coupon_type == i)
                    rang[i-1].checked = true;
            }
            var form = document.getElementsByName("form2");
            //data.data.cost_type = 1;
            for (var i = 1;i<form.length+1;i++){
                if (data.data.cost_type == i)
                    form[i-1].checked = true;
            }
            $("#Price2").val(data.data.price);

        })
    });

    //编辑卡券
    $(document).on("click",".edit",function() {
        var act_id = $(this).attr("act_id");
        $("#editCouponModal").modal();
        $("#editCoupon_id").attr("value",act_id);
        IO.get("/api/couponDetial",{act_id:act_id},function(data){
            $("#editCouponName").val(data.data.coupon_name);
            var startTime = data.data.dole_start_time.substring(0,10);
            var timeArry1 = startTime.split("/")
            startTime = timeArry1.join("-");
            var endTime = data.data.dole_end_time.substring(0,10);
            timeArry2= endTime.split("/")
            endTime = timeArry2.join("-");
            $("#editCouponTime1").val(startTime);
            $("#editCouponTime2").val(endTime);
            if (endTime == '2999-01-01'){
                var forever = document.getElementsByName("edittimeLimit");
                forever[0].checked = true;
            }
            $("#editEffective_time").val(data.data.day);
            $("#editCouponDiscount").val(data.data.discount*100);
            var totalCount = data.data.totalcount;
            var countLimt = document.getElementsByName("isCouponQuantity3");
            if (totalCount != -1){
                $("#editCouponQuantity").val(data.data.totalcount);
                countLimt[0].checked = false;
            }else{
                countLimt[0].checked = true;
            }
            var useLimt = data.data.limit_count;
            var Limt = document.getElementsByName("isLimit_count3");
            if (useLimt != -1){
                $("#editCouponLimit_count").val(data.data.limit_count);
                Limt[0].checked = false;
            }else{
                Limt[0].checked = true;
            }
            document.getElementById("editCouponInstro3").value = data.data.coupon_desc;
            $("#edit_pic").attr("src",data.data.coupon_cover);
            var rang = document.getElementsByName("editRange");
            for (var i = 1;i<rang.length+1;i++){
                if (data.data.coupon_type == i)
                    rang[i-1].checked = true;
            }
            var form = document.getElementsByName("editForm");
            for (var i = 1;i<form.length+1;i++){
                if (data.data.cost_type == i)
                    form[i-1].checked = true;
            }
            $("#editPrice").val(data.data.price);

        })
    });

    //确定编辑卡券
    $("#editCoupon").bind("click",function(){
        var name = $("#editCouponName").val();
        var start_time = $("#editCouponTime1").val();
        var end_time = $("#editCouponTime2").val();
        var timeLimit = document.getElementsByName("edittimeLimit");
        var timeLimitStr = '0';
        for (var i = 0;i <timeLimit.length;i++){
            if (timeLimit[i].checked){
                timeLimitStr = timeLimit[i].value;
            }
        }
        var effective_time = $("#editEffective_time").val();
        var couponDiscount = $("#editCouponDiscount").val();

        var CouponLimit_count = $("#editCouponLimit_count").val();
        var couponQuantity = $("#editCouponQuantity").val();
        var isLimit_count = document.getElementsByName("isLimit_count3");
        for (var i = 0;i <isLimit_count.length;i++){
            if (isLimit_count[i].checked){
                CouponLimit_count = isLimit_count[i].value;
            }
        }
        var isCouponQuantity = document.getElementsByName("isCouponQuantity3");
        for (var i = 0;i <isCouponQuantity.length;i++){
            if (isCouponQuantity[i].checked){
                couponQuantity = isCouponQuantity[i].value;
            }
        }

        var range = document.getElementsByName("editRange");
        var rangeStr='';
        for (var i = 0;i <range.length;i++){
            if (range[i].checked){
                rangeStr = range[i].value;
            }
        }
        var form = document.getElementsByName("editForm");
        var formStr='';
        for (var i = 0;i <form.length;i++){
            if (form[i].checked){
                formStr = form[i].value;
            }
        }
        var price = $("#editPrice").val();
        var couponInstro = document.getElementById("editCouponInstro3").value;

        var coupon_pic = $("#edit_pic").attr("src");


        if (name == ''){
            alert("请填写卡券名");
            return;
        }
        if (timeLimitStr == '0'){
            if (start_time == ''){
                alert("请填写可领取时间");
                return;
            }
            if (end_time == ''){
                alert("请填写可领取时间");
                return;
            }
            start_time += " 00:00:00";
            end_time += " 00:00:00";
        }else{
            var date = new Date();
            start_time = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate() + ' 00:00:00';
            end_time = '2999-1-1 00:00:00'
            //start_time = '';
            //end_time = '';
        }
        if (effective_time == ''){
            alert("请填写有效时间");
            return;
        }
        if (couponDiscount == ''){
            alert("请填写折扣面额");
            return;
        }else{
            couponDiscount = parseInt(couponDiscount)/100;
        }
        if (couponQuantity == ''){
            alert("请填写发行量");
            return;
        }
        if (rangeStr == ''){
            alert("请选择通用范围");
            return;
        }
        if (formStr == ''){
            alert("请选择卡券获取形式");
            return;
        }
        if (couponInstro == ''){
            alert("请填写详细介绍");
            return;
        }
        if (coupon_pic == '/images/ylm.png'){
            alert("请上传卡券图片");
            return;
        }
        var coupon_temp_id =  $("#editCoupon_id").val()
        var params = {coupon_temp_id:coupon_temp_id,name:name,start_time:start_time,end_time:end_time,timeLimitStr:timeLimitStr,
            effective_time:effective_time,couponDiscount:couponDiscount,CouponLimit_count:CouponLimit_count,couponQuantity:couponQuantity,rangeStr:rangeStr,formStr:formStr,price:price,couponInstro:couponInstro,coupon_pic:coupon_pic};
        //console.log("编辑卡券的参数",params);
        bootbox.confirm("确定编辑该卡券?",function(result) {
            if (result) {
                IO.get("/api/editCoupon", params, function (data) {
                    bootbox.alert(data.msg, function () {
                        if (data.code == 0) {
                            location.href = '/96053/card';
                        }
                    })
                })

            }
        })
    });

    //编辑卡券照片上传
    $('#edit_picfileupload').fileupload({
        url: '/upload',
        dataType: 'json',
        autoUpload: true,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        maxFileSize: 10000000, // 10 MB
        disableImageResize: /Android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
        previewMaxWidth: 150,
        previewMaxHeight: 150,
        previewCrop: true
    }).on('fileuploadadd', function (e, data) {
        document.getElementById('edit_pic').src = '/images/loading.gif';
    }).on('fileuploadprocessalways', function (e, data) {
        //console.log("fileuploadprocessalways",data);
    }).on('fileuploadprogressall', function (e, data) {
        //console.log("fileuploadprogressall",data);
    }).on('fileuploaddone', function (e, data) {
        var alt = $(e.target).attr('alt');
        if (!alt)
            alt = '';
        //console.log("#upimgs3" + alt);
        $("#edit_pic" + alt).attr("src", data._response.result.url);

    });

});